﻿using BLL;
using Models;
using Inspinia_MVC5.Code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Inspinia_MVC5.Controllers
{
    [AllowCors]
    public class RegisterController : Controller
    {
        // GET: Register注册
        public JsonResult Index(String name, String password)
        {
            PassswordHash x = new PassswordHash();
            AspNetRolesService AspNetRolesService = new AspNetRolesService();
            AspNetUsersService AspNetUsersService = new AspNetUsersService();
            AspNetUsers aspnetuser = AspNetUsersService.Find(u => u.UserName == name);
            AspNetRoles newrole = AspNetRolesService.Find(u => u.Name == "Worker");
            if (aspnetuser != null) 
            { 
                return Json(new { status = "5" }, JsonRequestBehavior.AllowGet);
            }
            aspnetuser.UserName = name;
            aspnetuser.PasswordHash = x.HashPassword(password);
            aspnetuser.Id = ResultHelper.NewId;
            aspnetuser.EmailConfirmed = false;
            aspnetuser.PhoneNumberConfirmed = false;
            aspnetuser.TwoFactorEnabled = false;
            aspnetuser.LockoutEnabled = true;
            aspnetuser.AccessFailedCount = 0;
            aspnetuser.AspNetRoles.Add(newrole);
            aspnetuser.Profession = ResultHelper.e2c(newrole.Name);
            try
            {
                AspNetUsersService.Add(aspnetuser);
            }
            catch (Exception e)
            {
                return Json(new { status = "7",message = e }, JsonRequestBehavior.AllowGet);
            }
            return Json(new { status = "0" }, JsonRequestBehavior.AllowGet);
        }
    }
}